import { Channel } from '@/types/data'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'


// state变量类型
export interface homeState {
  userChannelList: Channel[],
  restChannelList: Channel[],
  active: number
}
export const home = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'home',
  // 1. 定义变量(状态数据)
  initialState: {
    userChannelList: [],
    restChannelList: [],
    active: 0
  } as homeState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    setUserChannle(state, action: PayloadAction<Channel[]>) {
      state.userChannelList = action.payload
    },
    restUserChannle(state, action: PayloadAction<Channel[]>) {
      state.restChannelList = action.payload
    },
    setActive(state, action: PayloadAction<number>) {
      state.active = action.payload
    },
    delUserChannle(state, action: PayloadAction<Channel>) {
      state.userChannelList = state.userChannelList.filter(item => item.id !== action.payload.id)
      state.restChannelList.unshift(action.payload)
    },
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const { setUserChannle, restUserChannle, setActive, delUserChannle } = home.actions

// 导出reducer(创建store使用)
export default home.reducer